package com.cet.billingjob.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.batch.BatchDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.JdbcTransactionManager;

import javax.sql.DataSource;

/**
 * @author 30952
 */
@Configuration
public class DataSourceConfig {

    @Autowired
    private Environment env;

    @Bean
    @BatchDataSource
    public DataSource batchDataSource() {

        // SpringBoot默认使用Hikari数据库连接池
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(env.getProperty("spring.batchDataSource.url"));
        config.setUsername(env.getProperty("spring.batchDataSource.username"));
        config.setPassword(env.getProperty("spring.batchDataSource.password"));
        config.setDriverClassName("com.mysql.cj.jdbc.Driver");
        config.setMaximumPoolSize(50);
        config.setPoolName("batch_thread_pool");
        return new HikariDataSource(config);
    }

    @Primary
    @Bean
    public DataSource serviceDataSource() {

        // SpringBoot默认使用Hikari数据库连接池
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(env.getProperty("spring.serviceDataSource.url"));
        config.setUsername(env.getProperty("spring.serviceDataSource.username"));
        config.setPassword(env.getProperty("spring.serviceDataSource.password"));
        config.setDriverClassName("com.mysql.cj.jdbc.Driver");
        config.setMaximumPoolSize(50);
        config.setPoolName("service_thread_pool");
        return new HikariDataSource(config);
    }

    @Bean
    public JdbcTransactionManager batchTransactionManager(@Qualifier("batchDataSource") DataSource dataSource) {
        return new JdbcTransactionManager(dataSource);
    }

    @Bean("batchTemplate")
    public JdbcTemplate batchTemplate(@Qualifier("batchDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}
